package backend.project.gym_management.base.exception;

import backend.project.gym_management.base.response.JsonResult;
import backend.project.gym_management.base.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Objects;
@Slf4j
// GlobalExceptionHandler.java（统一异常处理）
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(RuntimeException.class)
    public JsonResult handleRuntimeException(RuntimeException ex) {
        log.debug(ex.getMessage());
        return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
    }

    @ExceptionHandler
    public JsonResult handleException(Exception ex) {
        return new JsonResult(StatusCode.UNKNOW_ERROR,ex.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JsonResult handleValidationException(MethodArgumentNotValidException ex) {
        String errorMsg = Objects.requireNonNull(ex.getBindingResult().getFieldError()).getDefaultMessage();
        return new JsonResult(StatusCode.VALIDATED_ERROR);
    }

    @ExceptionHandler
    public JsonResult handleIllegalArgumentException(IllegalArgumentException ex) {
        return new JsonResult(StatusCode.INVALID_PARAMETER,ex.getMessage());
    }
}